
class WxRequest {
  // 默认请求参数
  defaults = {
    baseURL: '',
    url: '',
    data: null,
    method: 'GET',
    header: {
      "Content-type": "application/json"
    },
    timeout: 60000
  }

  interceptors = {
    // 请求拦截器
    request: config => config,


    // 响应拦截器
    response: response => response


  }

  // 合并实例化传递的参数
  constructor(params={}) {
    this.defaults = Object.assign({}, this.defaults, params)
  }

  request(option) {
    option.url = this.defaults.baseURL + option.url
    let params = Object.assign({}, this.defaults, option)
    // option = {...this.defaults, ...option}

    // 在请求发送之前，添加 loading 效果
    wx.showLoading()

    // 请求拦截器
    params = this.interceptors.request(params)

    return new Promise((resolve, reject) => {
      wx.request({
        ...params,
        success: (res) => {
          // 响应成功后调用响应拦截器
          const mergeRes = Object.assign({}, res, {config: params, isSuccess: true})
          resolve(this.interceptors.response(mergeRes))
        },
        fail: (err) => {
          // 响应失败后调用响应拦截器
          const mergeErr = Object.assign({}, err, {config: params, isSuccess: false})
          reject(this.interceptors.response(mergeErr))
        },
        complete() {
          wx.hideLoading()
        }
      })
    })
  }

  get(url, data={}, config={}) {
    return this.request({url, data, method: 'GET', ...config})
  }

  post(url, data={}, config={}) {
    return this.request({url, data, method: 'POST', ...config})
  }

  put(url, data={}, config={}) {
    return this.request({url, data, method: 'PUT', ...config})
  }

  delete(url, data={}, config={}) {
    return this.request({url, data, method: 'DELETE', ...config})
  }

  all(...promise) {
    return Promise.all(promise)
  }
}

export default WxRequest
